package com.zyg.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.dao.PermissionMapper;
import com.zyg.pojo.Permission;
import com.zyg.service.PermissionService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service("permissionService")
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Override
    public List<Permission> list() {

        List<Permission> permissions = baseMapper.selectList(null);
        // 创建根集合
        List<Permission> root = permissions.stream().filter(p -> p.getParentId() == 0).toList();
        // 递归给根集合设置子节点
        root.forEach(p -> {
            p.setChildren(getChildren(p.getId(), permissions));
            p.setIsParent(p.getChildren().size() > 0);
        });
        return root;
    }

    private List<Permission> getChildren(Integer id, List<Permission> permissions) {
        List<Permission> children = new ArrayList<>();
        permissions.forEach(p -> {
            if (p.getParentId() != null && p.getParentId().equals(id)) {
                p.setChildren(getChildren(p.getId(), permissions));
                p.setIsParent(p.getChildren().size() > 0);
                children.add(p);
            }
        });
        return children;
    }
}